package com.zb.session;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import com.zb.common.utils.SerializeUtil;
import com.zb.common.utils.SpringHelper;

/**
 * 分布式session实现Service
 * 
 * @version
 * @since JDK 1.7
 */
public class SessionService {

    private static final Logger logger = Logger.getLogger(SessionService.class);

    private static SessionService instance = null;
    private JedisPool redisConnectionPool;
    private String redisSessionKey = "zb:distributed:sessionid:";

    public static synchronized SessionService getInstance() {
        if (instance == null) {
            instance = new SessionService();
        }
        return instance;
    }

    private SessionService() {
        redisConnectionPool = (JedisPool) SpringHelper.getBean("redisConnectionPool");
    }

    /**
     * 
     * getSession:(获取Session). <br/>
     *
     * @author 多多洛
     * @param sid
     * @return
     * @since JDK 1.7
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> getSession(String sid) {
        Jedis jedis = null;
        Map<String, Object> session = new HashMap<String, Object>();
        try {
            jedis = redisConnectionPool.getResource();
            String key = redisSessionKey + sid;
            byte[] resultData = jedis.get(key.getBytes());
            Object resultObj = SerializeUtil.unserialize(resultData);
            if (null == resultData || null == resultObj) {
                return session;
            }
            session = (Map<String, Object>) resultObj;
        } catch (Exception e) {
            redisConnectionPool.returnBrokenResource(jedis);
            jedis = null;
            e.printStackTrace();
            logger.error(
                    "[SessionService][getSession] 获取session出现异常: sid: " + sid
                            + "-" + e.getLocalizedMessage() + ":"
                            + e.getMessage(), e.getCause());
        } finally {
            if (redisConnectionPool != null && jedis != null) {
                redisConnectionPool.returnResource(jedis);
            }
        }
        return session;
    }

    /**
     * 
     * saveSession:(保存Session). <br/>
     *
     * @author 多多洛
     * @param sid
     * @param session
     * @param seconds
     * @since JDK 1.7
     */
    public void saveSession(String sid, Map<String, Object> session, int seconds) {
        Jedis jedis = null;
        try {
            jedis = redisConnectionPool.getResource();
            String key = redisSessionKey + sid;
            logger.info("[SessionService][saveSession] 保存session的key: " + key);
            String result = jedis.setex(key.getBytes(), seconds,
                    SerializeUtil.serialize(session));
            logger.info("[SessionService][saveSession] 保存session的结果为: "
                    + result);
        } catch (Exception e) {
            redisConnectionPool.returnBrokenResource(jedis);
            jedis = null;
            e.printStackTrace();
            logger.error("[SessionService][saveSession] 保存session出现异常: sid: "
                    + sid + " session: " + session + " seconds: " + seconds
                    + "-" + e.getLocalizedMessage() + ":" + e.getMessage(),
                    e.getCause());
        } finally {
            if (redisConnectionPool != null && jedis != null) {
                redisConnectionPool.returnResource(jedis);
            }
        }
    }

    /**
     * 
     * removeSession:(删除Session). <br/>
     *
     * @author 多多洛
     * @param sid
     * @since JDK 1.7
     */
    public void removeSession(String sid) {
        logger.info("[SessionService][removeSession] 删除session的sid: " + sid);
        Jedis jedis = null;
        try {
            jedis = redisConnectionPool.getResource();
            String key = redisSessionKey + sid;
            logger.info("[SessionService][removeSession] 删除session的key: " + key);
            long result = jedis.del(key);
            logger.info("[SessionService][removeSession] 删除session的结果为: "
                    + (result == 1));
        } catch (Exception e) {
            redisConnectionPool.returnBrokenResource(jedis);
            jedis = null;
            e.printStackTrace();
            logger.error(
                    "[SessionService][removeSession] 删除session出现异常: sid: "
                            + sid + "-" + e.getLocalizedMessage() + ":"
                            + e.getMessage(), e.getCause());
        } finally {
            if (redisConnectionPool != null && jedis != null) {
                redisConnectionPool.returnResource(jedis);
            }
        }
    }
}
